#!/usr/local/bin/perl

package Armory::Guild;
use strict;

use Armory::Char;
use LWP::UserAgent;
use XML::Simple;
use Data::Dumper;

sub new {
	my ($perlclass, %conf) = @_;
	my $self  = {};
	$self->{NAME}   = $conf{'name'} || undef;
	$self->{REALM}  = $conf{'realm'} || undef;
	bless($self, $perlclass);
	return $self;
}

sub name {
	my $self = shift;
	if (@_) { $self->{NAME} = shift }
	return $self->{NAME};
}

sub realm {
	my $self = shift;
	if (@_) { $self->{REALM} = shift }
	return $self->{REALM};
}

sub battlegroup {
	my $self = shift;
	return $self->{BATTLEGROUP};
}

sub membercount {
	my $self = shift;
	return $self->{MEMBERCOUNT};
}

sub faction {
	my $self = shift;
	return $self->{FACTION};
}

sub members {
	my $self = shift;
	return sort keys %{$self->{MEMBERS}};
}

sub member {
	my $self = shift;
	my $name = shift;
	return $self->{MEMBERS}->{$name} || 0;
}

sub fetch {
	my $self = shift;
	if (@_) { 
		my %conf = @_;
		$self->{NAME} = $conf{'name'} || $self->{NAME};
		$self->{REALM} = $conf{'realm'} || $self->{REALM};
	}

	my $baseurl = "http://armory.worldofwarcraft.com/guild-info.xml";

	my $ua = LWP::UserAgent->new( 'agent' => 'Firefox/2.0' );
	my $response = $ua->get($baseurl . '?r=' . $self->{REALM} . '&n=' . $self->{NAME} . '&p=1');

	if (! $response->is_success) {
		return 0;
	}

	my $ref = XMLin($response->content);

	my $guildinfo = $ref->{'guildInfo'}->{'guild'};
	my $members = $guildinfo->{'members'};
	my $pages = $members->{'maxPage'};

	$self->{BATTLEGROUP} = $guildinfo->{'battleGroup'};
	$self->{MEMBERCOUNT} = $members->{'memberCount'};

	$self->_snarfnames($members->{'character'});

	if ($pages > 1) {
		foreach my $i (2..$pages) {
			$response = $ua->get($baseurl . '?r=' . $self->{REALM} . '&n=' . $self->{NAME} . '&p=' . $i);
			$ref = XMLin($response->content);
			$self->_snarfnames($ref->{'guildInfo'}->{'guild'}->{'members'}->{'character'});
		}
	}

	return 1;
}

sub _snarfnames {
	my $self = shift;
	my $memberlist = shift;

	foreach my $memb (keys %{$memberlist}) {
		my $char = Armory::Char->new(
				'realm' => $self->{REALM}, 
				'name' => $memb,
				);
		$char->level($memberlist->{$memb}->{'level'});
		$char->race($memberlist->{$memb}->{'race'});
		$char->class($memberlist->{$memb}->{'class'});
		$char->gender($memberlist->{$memb}->{'gender'});
		# rank also available; not implemented in Char.pm

		$self->{MEMBERS}->{$memb} = $char;
	}
}

1;
